# 从migu的html视频页中获取m3u8的链接 

from selenium import webdriver  
from selenium.webdriver.common.by import By  
from selenium.webdriver.support.ui import WebDriverWait  
from selenium.webdriver.support import expected_conditions as EC  
from selenium.webdriver.common.action_chains import ActionChains
import time
import sys, json

import undetected_chromedriver as uc
from selenium.webdriver.chrome.options import Options


# =========================================
# 剧集TV 电视剧解析 https://www.ijujitv.cc  https://www.ijujitv.cc/detail/51805.html
# =========================================

def scrollToElement(driver, element) :
    driver.execute_script("arguments[0].scrollIntoView();", element)

def clickElement(driver, element) :

    scrollToElement(driver, element)
    time.sleep(1)

    # 获取鼠标指针的当前位置  
    mouse_position = driver.execute_script("return {x: window.screenX, y: window.screenY}")  
    
    # 构建鼠标点击的动作链  
    actions = ActionChains(driver)  
    actions.move_to_element(element)  # 将鼠标指针移动到div元素的位置  
    actions.click()  # 触发点击事件 
    # 执行动作链并等待点击事件完成  
    actions.perform() 

def openMiguHtml2(ttUploadVideoUrl) :

    driver = webdriver.Chrome()
    driver.maximize_window()

    #ul = 'https://mp.toutiao.com/profile_v4/xigua/upload-video?from=toutiao_pc'
    driver.get(ttUploadVideoUrl)
    return driver


    chrome_options = Options()

    # chrome 默认的profile路径
    profile = '/Users/wkun/Library/Application Support/Google/Chrome/Default'

    # 将默认的profile路径中的内容，拷贝到以下目录中，并将该路径指派给chromedriver
    profile = '/Users/wkun/Documents/Projects/Bill/GiteePython/miguautomedia/profile/Default'

    #profile = '/Users/cgw/Desktop/Files/Codes/Gitee/Python/automedia/profile/Default'



    # 每次打开浏览器之前，先重置用户数据目录即：--user-data-dir 的目录的内容 
    # zip_file = '/Users/cgw/Desktop/Files/Codes/Gitee/Python/automedia/profile/Default.zip'
    # to_path = '/Users/cgw/Desktop/Files/Codes/Gitee/Python/automedia/profile/'
    # ret = reset.reset_chrome_user_dir(zip_file, to_path, profile)
    # if ret != 1 :
    #     print('err: 重置浏览器用户数据目录失败')
    #     return None
    # print('重置浏览器用户数据目录成功了')


    chrome_options.add_argument(f"--user-data-dir={profile}")

    # 手动下载好chromedriver，然后手动指定driver_executable_path，免得自动去下载，会被和谐
    driverpath = '/Users/wkun/Documents/Projects/Bill/GiteePython/miguautomedia/profile/driver/chromedriver'
    #driverpath = '/Users/cgw/Desktop/Files/Codes/Gitee/Python/automedia/profile/chromedrive/chromedriver'
    driver = uc.Chrome(options=chrome_options ,driver_executable_path=driverpath)
    driver.maximize_window()

    time.sleep(10)
    #ul = 'https://mp.toutiao.com/profile_v4/xigua/upload-video?from=toutiao_pc'
    driver.get(ttUploadVideoUrl)

    return driver

def get_m3u_url(driver) :
    iframes = driver.find_elements(By.TAG_NAME, "iframe")
    for fa in iframes :
        src = fa.get_property('src')
        if type(src) == str : 
            prefix = 'https://jx.ijujitv.cc/player/?url='
            if (prefix in src) and ('m3u8' in src) :
                # 得到m3u8的链接
                m3u8Url = src.replace(prefix, '')
                return m3u8Url

    return None

def get_all_video_html(driver) :

    # 找到所有class为autowidth的a标签（第几集）
    taga = driver.find_elements(By.XPATH, "//a[@class='autowidth']")
    if len(taga) == 0 :
        print('获取剧集链接失败')
        return

    names = []
    urls = []
    for a in taga :
        
        # 找到第几集
        name = a.text
        print(f'开始寻找剧集的a标签:{name}')
        if ('第' in name) and ('集' in name) :
            videoUrl = a.get_property('href')
            if type(videoUrl) == str and len(videoUrl) > 5 :
                urls.append(videoUrl)
                names.append(name)
            else :
                print(f'获取url失败:{name}')
                continue

        else :
            print(f'标签-{name}-不是视频url的标签')
            continue

    return (urls, names)

def get_one_url(driver, htmlurl) :
    driver.get(htmlurl)

    # 获取m3u8的地址
    times = 0
    m3u8 = None 
    while(True) :
        m3u8 = get_m3u_url(driver)
        # 若获取失败, 则1秒后再次获取
        if m3u8 == None :
            time.sleep(1)
            times += 1
            # 若重试10次都失败，则跳过本url获取
            if times > 10 :
                break
        else :
            break

    return m3u8


def parse_jjtv(videoUrl) :

    driver = openMiguHtml2(videoUrl)

    print('等待3秒加载页面')
    time.sleep(3)

    urls, names = get_all_video_html(driver)

   
    #return 

    if len(urls) == 0 or len(names) == 0:
        print('取得所有视频的html地址失败')
        return 

    print('取得所有的url地址')
    print(names)
    print(urls)

    jsonArr = []
    count = min(len(urls), len(names))
    for i in range(count) :
        url = urls[i]
        na = names[i]

        print(f'开始获取第{i}个m3u8地址')
        m3u = get_one_url(driver, url)
        if m3u == None :
            print(f'获取m3u8失败：{na} - {url}')
            continue

        json = {'name': na, 'src': curl, 'm3u8Url': m3u}
        jsonArr.append(json)


    if len(jsonArr) == 0 :
        print('获取所有剧集m3u8失败')
        return 

    print('得到所有剧集的m3u8链接')
    jsonFilePath = './m3u8.json'
    with open(jsonFilePath, "w", encoding='utf-8') as file:  
        json.dump(jsonArr, file, ensure_ascii=False)
        print('json数据保存完成！！文件名：m3u8.json')


print("欢迎使用-剧集tv解析-工具! 仅供技术研究，请勿商用!!!")
print("示例地址：https://www.ijujitv.cc/detail/24157.html")
tvurl = (input(f"请输入电视剧的首页地址："))
if tvurl == None or len(tvurl) < 5 :
    print('地址不正确')
    exit()

if 'http' not in tvurl : 
    print('地址不正确')
    exit()

print("即将自动打开谷歌浏览器")
time.sleep(1.5)
print(f'开始解析：{tvurl}')
parse_jjtv(tvurl)
print('解析结束！')


